package vn.njai.thousand_english_word.Activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.*;
import android.widget.*;
import butterknife.ButterKnife;
import butterknife.InjectView;
import com.fortysevendeg.swipelistview.BaseSwipeListViewListener;
import com.fortysevendeg.swipelistview.SwipeListView;
import com.google.android.gms.ads.AdRequest;
import vn.njai.thousand_english_word.ChatHead.ChatHeadService;
import vn.njai.thousand_english_word.CustomUI.CustomMenuView;
import vn.njai.thousand_english_word.Entities.HistoryData;
import vn.njai.thousand_english_word.Entities.Learning;
import vn.njai.thousand_english_word.Entities.NodeItem;
import vn.njai.thousand_english_word.R;
import vn.njai.thousand_english_word.Utils.DataManager;
import vn.njai.thousand_english_word.Utils.Utils;

import java.util.ArrayList;


public class MainActivity extends ActionBarActivity implements MediaPlayer.OnCompletionListener{
    private String TAG = "MainActivity";
    private Context mContext;
    private ActionBarDrawerToggle mDrawerToggle;
    private ItemAdapter mAdapter;
    private boolean mMeasured = false;
    //private boolean mMeasuredAd = false;
    private int mListHeight;
    public static MainActivity me;
    public int StatusClose = 0;

    @InjectView(R.id.example_swipe_lv_list) public SwipeListView mSwipeListVIew;
    @InjectView(R.id.drawer_layout) public DrawerLayout mDrawerLayout;
    @InjectView(R.id.menuLayout) public CustomMenuView mMenuView;
    @InjectView(R.id.toolbar) public Toolbar mToolbar;
    //@InjectView(R.id.adView) public AdView mAdView;

    public static void start(Context context) {
        Intent intent = new Intent(context,MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        me = this;
        setContentView(R.layout.activity_main);
        mContext = this;
        ButterKnife.inject(this);
        initActionBar();

        AdRequest adRequest = new AdRequest.Builder()
                .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                .build();

        //mAdView.loadAd(adRequest);
        mToolbar.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (!mMeasured) {
                    mMeasured = true;
//                    mAdView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
//                        @Override
//                        public void onGlobalLayout() {
//                            if (!mMeasuredAd) {
//                                mMeasuredAd = true;
                                init();
//                            }
//                        }
//                    });
                }
            }
        });
    }

    @Override
    protected void onPostResume() {
        stopService(new Intent(this, ChatHeadService.class));
        super.onPostResume();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId())
        {
            case R.id.action_pin:
                ChatHeadService.mContext = mContext;
                mContext.startService(new Intent(mContext, ChatHeadService.class));
                finish();
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.message_activity_action, menu);
        return super.onCreateOptionsMenu(menu);
    }

    private void init(){
        mListHeight = getListHeight();
        initNodeItem();
        initMenuView();
        initSwipeListView();
    }

    private void initNodeItem(){
        DataManager.getInstance().loadLearningList();
        DataManager.getInstance().loadNeedLearnList();
        DataManager.getInstance().loadHistoryList();
        if(DataManager.getInstance().mHistoryData == null) {
            DataManager.getInstance().mHistoryData = new HistoryData();
        }
        if(DataManager.getInstance().mLearning == null) {
            DataManager.getInstance().mLearning = new Learning();
            for(int i = 0;i<5;i++){
                NodeItem nodeItem = DataManager.getInstance().getRandomNode();
                if(nodeItem != null)
                    DataManager.getInstance().mLearning.mLearningList.add(nodeItem);
            }
            DataManager.getInstance().saveLearningList();
            DataManager.getInstance().saveNeedLearnList();
        }

        mAdapter = new ItemAdapter();
        mAdapter.addAll(DataManager.getInstance().mLearning.mLearningList);
    }

    private void initSwipeListView(){
        mSwipeListVIew.setSwipeListViewListener(new BaseSwipeListViewListener() {

            @Override
            public void onClickFrontView(int position) {
                StatusClose = 0;
                mSwipeListVIew.openAnimate(position); //when you touch front view it will open
            }

            @Override
            public void onClickBackView(int position) {
                mSwipeListVIew.closeAnimate(position);//when you touch back view it will close
            }

            @Override
            public void onDismiss(int[] reverseSortedPositions) {
                for (int index : reverseSortedPositions) {
                    if(StatusClose == 2)
                        updateNode(index);
                    if(StatusClose == 1)
                        removeNode(index);
                }
            }
        });

        mSwipeListVIew.setSwipeMode(SwipeListView.SWIPE_MODE_LEFT);
        mSwipeListVIew.setSwipeActionLeft(SwipeListView.SWIPE_ACTION_REVEAL);
        mSwipeListVIew.setOffsetLeft(Utils.mScreenWeight - mListHeight / 3);
        mSwipeListVIew.setAnimationTime(250);
        mSwipeListVIew.setAdapter(mAdapter);
    }

    public void removeNode(int index){
        DataManager dataManager = DataManager.getInstance();
        //giu lai mau da xoa
        int oldColor = mAdapter.getItem(index).mColor;
        //xoa dong tren giao dien
        mAdapter.remove(mAdapter.getItem(index));
        //update gia tri da hoc la 3
        NodeItem nodeItemUpDate = DataManager.getInstance().mLearning.mLearningList.get(index);
        nodeItemUpDate.mRemember = 3;
        DataManager.getInstance().setWordAt(nodeItemUpDate);
        //xoa tu dang hoc
        DataManager.getInstance().mHistoryData.mListHistory.add(nodeItemUpDate.mRank);
        DataManager.getInstance().mLearning.mLearningList.remove(index);
        //tao ra tu moi
        NodeItem nodeItem = DataManager.getInstance().getRandomNode(oldColor);
        //them vao dang hoc
        if (nodeItem != null) {
            DataManager.getInstance().mLearning.mLearningList.add(nodeItem);
            //them vao adapter neu co tu
            mAdapter.insert(nodeItem, mAdapter.getCount());
        }
        //luu lai
        DataManager.getInstance().saveLearningList();
        DataManager.getInstance().saveNeedLearnList();
        DataManager.getInstance().saveHistoryList();
        //dong animation
        mSwipeListVIew.closeAnimate(index);
    }

    public void updateNode(int index) {
        //neu da hoc 3 lan thi xoa
        DataManager dataManager = DataManager.getInstance();
        if (DataManager.getInstance().mLearning.mLearningList.get(index).mRemember == 2) {
        removeNode(index);
        }else {
            //giu lai mau cu
            int oldColor = mAdapter.getItem(index).mColor;
            //xoa dong tren giao dien
            mAdapter.remove(mAdapter.getItem(index));
            //cong them mot lan hoc
            NodeItem nodeItemUpDate = DataManager.getInstance().mLearning.mLearningList.get(index);
            //add lai need learn
            DataManager.getInstance().mNeedLearn.mNeedLearnList.add(nodeItemUpDate.mRank);
            if(nodeItemUpDate.mRemember!=3)
                nodeItemUpDate.mRemember += 1;

            //luu xuong
            DataManager.getInstance().setWordAt(nodeItemUpDate);
            //xoa trong danh sach dang hoc
            DataManager.getInstance().mHistoryData.mListHistory.add(nodeItemUpDate.mRank);
            DataManager.getInstance().mLearning.mLearningList.remove(index);
            //tao tu moi
            NodeItem nodeItem = DataManager.getInstance().getRandomNode(oldColor);
            if (nodeItem != null){
                //them vao danh sách dang hoc
                DataManager.getInstance().mLearning.mLearningList.add(nodeItem);
                //them vao giao dien
                mAdapter.insert(nodeItem, mAdapter.getCount());
            }
        }
        //luu lai
        DataManager.getInstance().saveLearningList();
        DataManager.getInstance().saveNeedLearnList();
        DataManager.getInstance().saveHistoryList();
        //dong aninmation
        mSwipeListVIew.closeAnimate(index);
    }

    private void initMenuView(){
        mMenuView.setDrawerLayout(mDrawerLayout);
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.app_name, R.string.app_name) {

            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                invalidateOptionsMenu();
            }
        };
        mDrawerToggle.syncState();
    }

    private void initActionBar(){
        mToolbar.setTitle(this.getString(R.string.actionbar_title_main));
        mToolbar.setNavigationIcon(R.drawable.ic_menu_home);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolbar.refreshDrawableState();
    }

    private int getListHeight(){
        int actionBarHeight = mToolbar.getMeasuredHeight();
        //return Utils.mScreenHeight - actionBarHeight - Utils.getStatusBarHeight(mContext)- mAdView.getMeasuredHeight();
        return Utils.mScreenHeight - actionBarHeight - Utils.getStatusBarHeight(mContext);
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        if(mediaPlayer!=null)
            mediaPlayer.release();
    }

    public class ItemAdapter extends ArrayAdapter<NodeItem> {

        public ItemAdapter() {
            super(mContext, 0, new ArrayList<NodeItem>());
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            View view = convertView;
            final NodeItem item = getItem(position);

            if(view == null){
                LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
                view = inflater.inflate(R.layout.custom_node_main, parent, false);
                view.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, mListHeight / 5));
                holder = new ViewHolder(view);
                view.setTag(holder);
            }
            else{
                holder = (ViewHolder)view.getTag();
            }

            holder.imageBackground.setBackgroundColor(item.mColor);
            holder.txtWord.setText(item.mWord);
            holder.txtMeans.setText(item.mMeans);
            holder.txtPhonetic.setText(item.mPhonetic);
            holder.txtRank.setText(String.valueOf(item.mRank));
            holder.btnClose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(StatusClose == 0) {
                        StatusClose = 1;
                        mSwipeListVIew.closeAnimate(position);
                        mSwipeListVIew.clearAnimation();
                        mSwipeListVIew.dismiss(position);
                    }
                }
            });
            holder.btnCheck.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(StatusClose == 0) {
                        StatusClose = 2;
                        mSwipeListVIew.closeAnimate(position);
                        mSwipeListVIew.clearAnimation();
                        mSwipeListVIew.dismiss(position);
                    }
                }
            });
            holder.txtType.setText(item.mType);
            switch (item.mRemember){
                case 0:
                    holder.imgCount1.setVisibility(View.GONE);
                    holder.imgCount2.setVisibility(View.GONE);
                    break;
                case 1:
                    holder.imgCount1.setVisibility(View.VISIBLE);
                    holder.imgCount2.setVisibility(View.GONE);
                    break;
                case 2:
                    holder.imgCount1.setVisibility(View.VISIBLE);
                    holder.imgCount2.setVisibility(View.VISIBLE);
                    break;
            }
            holder.btnSound.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Handler handler = new Handler();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            try {

                                MediaPlayer mediaPlayer = new MediaPlayer();
                                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                                String url = "http://soundoftext.com/audio/English/" + item.mWord.toLowerCase() + ".mp3";
                                DataManager.getInstance().loadVolume();
                                mediaPlayer.setVolume((float)DataManager.getInstance().mVolume/100,(float)DataManager.getInstance().mVolume/100);
                                mediaPlayer.setDataSource(url);
                                mediaPlayer.prepare(); // might take long! (for buffering, etc)
                                mediaPlayer.start();
                            }catch (Exception ex){

                            }
                        }
                    });
                }
            });
            return view;
        }

        public class ViewHolder{
            @InjectView(R.id.btnClose) public ImageButton btnClose;
            @InjectView(R.id.btnCheck) public ImageButton btnCheck;
            @InjectView(R.id.imgCount1) public ImageView imgCount1;
            @InjectView(R.id.imgCount2) public ImageView imgCount2;
            @InjectView(R.id.imgBackground) public ImageView imageBackground;
            @InjectView(R.id.txtWord) public TextView txtWord;
            @InjectView(R.id.txtMeans) public TextView txtMeans;
            @InjectView(R.id.txtPhonetic) public TextView txtPhonetic;
            @InjectView(R.id.txtRank) public TextView txtRank;
            @InjectView(R.id.btnSound) public ImageButton btnSound;
            @InjectView(R.id.txtType) public TextView txtType;

            public ViewHolder(View view){
                ButterKnife.inject(this, view);
            }
        }

    }

//    /** Called when leaving the activity */
//    @Override
//    public void onPause() {
//        if (mAdView != null) {
//            mAdView.pause();
//        }
//        super.onPause();
//    }
//
//    /** Called when returning to the activity */
//    @Override
//    public void onResume() {
//        super.onResume();
//        if (mAdView != null) {
//            mAdView.resume();
//        }
//    }
//
//    /** Called before the activity is destroyed */
//    @Override
//    public void onDestroy() {
//        if (mAdView != null) {
//            mAdView.destroy();
//        }
//        super.onDestroy();
//    }
}
